// pages/category/category.js
import {Category} from 'category-model.js';
var category = new Category();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    transClassArr: ['tanslate0', 'tanslate1', 'tanslate2', 'tanslate3', 'tanslate4', 'tanslate5'],
    currentMenuIndex:0,
    loadingHidden:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._loadData();
  },

  /**
   * 加载所有数据
   */
  _loadData:function(callback){
    var that = this;
    category.getCategoryType((categoryData)=>{

      that.setData({
        categoryTypeArr:categoryData,
        loadingHidden:true
      });

      that.getProductsByCategory(categoryData[0].id,(data)=>{
        var dataObj = {
          products:data,
          topImgUrl:categoryData[0].img.url,
          title:categoryData[0].name
        };
        that.setData({
          loadingHidden:true,
          categoryInfo0:dataObj
        });
        callback && callback();
      });
    });
  },

  /**
   * 切换分类
   */
  changeCategory:function(event){
    var index = category.getDataSet(event,'index');
    var id = category.getDataSet(event,'id');
    this.setData({
      currentMenuIndex:index
    });

    if (!this.isLoadedData(index)){
      var that = this;

      this.getProductsByCategory(id, (data) => {
        that.setData(that.getDataObjForBind(index, data));
      });
    }
    
  },

  /**
   * 判断是否是第一次点击
   */
  isLoadedData:function(index){
    if(this.data['categoryInfo' + index]){
      return true;
    }else{
      return false;
    }
  },

  /**
   * 得到当前分类下的商品数据
   */
  getDataObjForBind:function(index,data){
    var obj = {},
    arr = [0,1,2,3,4,5],
    baseData = this.data.categoryTypeArr[index];
    // for(var item in arr){
      // if(item == arr[index]){
        obj['categoryInfo' + index] = {
          products:data,
          topImgUrl:baseData.img.url,
          title:baseData.name
        }
        return obj;
      // }
    // }
  },

  /**
   * 获得具体分类下的商品
   */
  getProductsByCategory:function(id,callback){
    category.getProductsByCategory(id,(data)=>{
      callback && callback(data);
    });
  },

  /**
   * 跳转到商品详情
   */
  onProductsItemTap:function(event){
    var id = category.getDataSet(event,'id');
    wx.navigateTo({
      url: '../product/product?id=' + id
    })
  },

  /**
   * 下拉刷新页面
   */
  onPullDownRefresh:function(){
    this._loadData(()=>{
      wx.stopPullDownRefresh();
    });
  }
})